package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.CheckGroupDao;
import com.itheima.dao.CheckItemDao;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.CheckItem;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private SetmealDao setmealDao;
    @Autowired
    private JedisPool jedisPool;
    @Autowired
    private CheckGroupDao checkGroupDao;
    @Autowired
    private CheckItemDao checkItemDao;
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;
    @Value("${out_p" + "ut_path}")
    private String outPutPath;

    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage, pageSize);
        Page<Setmeal> setmeals = setmealDao.findByQueryString(queryString);
        long total = setmeals.getTotal();
        List<Setmeal> setmealList = setmeals.getResult();
        return new PageResult(total, setmealList);
    }

    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        setmealDao.add(setmeal);
        Integer setmealId = setmeal.getId();
        if (checkgroupIds.length > 0) {
            setmealDao.insertSetmealIdAndCheckgroupId(setmealId, checkgroupIds);
        }
        String fileName = setmeal.getImg();
        //保存套餐时将图片名称添加到redis集合中
//        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,fileName);
        generateMobileStaticHtml();
    }

    @Override
    public void deleteByid(String id) {
        setmealDao.deleteSetmealIdAndCheckgroupId(id);
        setmealDao.deleteByid(id);
    }

    @Override
    public Setmeal setmealUpdate(Integer id) {
        return setmealDao.setmealUpdate(id);
    }

    @Override
    public Integer[] findSetmealByCheckGroupIds(Integer id) {
        return setmealDao.findSetmealByCheckGroupIds(id);
    }

    @Override
    public void handleUpdate(Setmeal setmeal, Integer[] checkgroupIds) {
        setmealDao.handleUpdate(setmeal);
        Integer setmealId = setmeal.getId();
        setmealDao.deleteSetmealIdAndCheckgroupId(setmealId.toString());
        if (checkgroupIds.length > 0) {
            setmealDao.insertSetmealIdAndCheckgroupId(setmealId, checkgroupIds);
        }
    }

    @Override
    public List<Setmeal> getAllSetmeal() {
        return setmealDao.getAllSetmeal();
    }

    @Override
    public Setmeal findById(Integer id) {
        Setmeal setmeal = setmealDao.findById(id);
        Integer[] checkGroupIds = setmealDao.findSetmealByCheckGroupIds(id);
        ArrayList<CheckGroup> checkGroupList = new ArrayList<>();
        for (Integer checkGroupId : checkGroupIds) {
            CheckGroup checkGroup = checkGroupDao.findById(checkGroupId);
            Integer[] checkItemIds = checkGroupDao.findCheckItemIdsByCheckGroupId(checkGroupId);
            ArrayList<CheckItem> checkItemlist = new ArrayList<>();
            for (Integer checkItemId : checkItemIds) {
                CheckItem checkItem = checkItemDao.findByid(checkItemId);
                checkItemlist.add(checkItem);
            }
            checkGroup.setCheckItems(checkItemlist);
            checkGroupList.add(checkGroup);
        }
        setmeal.setCheckGroups(checkGroupList);
        System.out.println(setmeal);
        return setmeal;
    }

    @Override
    public List<Map<String, Object>> getSetmealReport() {
        return setmealDao.findSetmealCount();
    }


    //生成当前方法所需的静态页面
    public void generateMobileStaticHtml() {
        List<Setmeal> list = setmealDao.getAllSetmeal();
        generateMobileSetmealDetailHtml(list);
        generateMobileSetmealListHtml(list);
    }

    //生成套餐列表静态信息
    public void generateMobileSetmealListHtml(List<Setmeal> list) {
        Map<String, Object> map = new HashMap<>();
        map.put("setmealList", list);
        generteHtml("mobile_setmeal.ftl", "m_setmeal.html", map);
    }

    //生成套餐详细静态页面
    public void generateMobileSetmealDetailHtml(List<Setmeal> list) {
        for (Setmeal setmeal : list) {
            Setmeal setmeal1 = this.findById(setmeal.getId());
            System.out.println(setmeal1);
            Map<String, Object> map = new HashMap<>();
            map.put("setmeal", setmeal1);
            generteHtml("mobile_setmeal_detail.ftl", "setmeal_detail" + setmeal.getId() + ".html", map);
        }
    }

    //通用的方法，用于生成静态页面
    public void generteHtml(String templateName, String htmlPageName, Map map) {
        Configuration configuration = freeMarkerConfigurer.getConfiguration();//获得配置对象
        Writer out = null;
        try {
            Template template = configuration.getTemplate(templateName);
            //构造输出流
            new OutputStreamWriter(new FileOutputStream(outPutPath + "/" + htmlPageName), "utf-8");

            out = new FileWriter(new File(outPutPath + "/" + htmlPageName));
            //输出文件
            template.process(map, out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
